import 'package:flutter_test/flutter_test.dart';
import 'package:m_todo/domain/entity/account_entity.dart';
import 'package:m_todo/domain/service/account_service.dart';
import 'package:m_todo/domain/store/base_account_store.dart';
import 'package:m_todo/domain/use_case/account_use_case.dart';
import 'package:m_todo/store/file_account_store.dart';

main() async {
  var defAccounts = [AccountEntity(name: '111', password: '111'), AccountEntity(name: '222', password: '222')];
  var fileStore = FileAccountStore();
  await fileStore.init(defAccounts, login: null);
  var useCase = AccountUseCase(AccountService(fileStore));
  group('测试AccountUseCase', () {
    test('测试login', () async {
      var loginAccount = await useCase.getLoginAccount();
      expect(loginAccount, null);

      var l1 = await useCase.login('111', '11');
      expect(l1, LoginState.invalidPassword);

      loginAccount = await useCase.getLoginAccount();
      expect(loginAccount, null);

      var s2 = await useCase.login('1', '111');
      expect(s2, LoginState.invalidUserName);

      var s3 = await useCase.login('111', '111');
      expect(s3, LoginState.success);

      loginAccount = await useCase.getLoginAccount();
      expect(loginAccount?.name, '111');

      var s4 = await useCase.login('111', '111');
      expect(s4, LoginState.repeatLogin);
    });

    test('测试logout', () async {
      await useCase.logout();
      expect(await useCase.getLoginAccount(), null);
    });
  });
}

class _FakeAccountStore extends BaseAccountStore {
  final List<AccountEntity> repository;
  AccountEntity? loginAccount;

  _FakeAccountStore(this.repository, this.loginAccount);

  @override
  Future<void> clearLoginAccount() {
    loginAccount = null;
    return Future.value();
  }

  @override
  Future<AccountEntity?> getLoginAccount() {
    return Future.value(loginAccount);
  }

  @override
  Future<AccountEntity?> queryAccountByName(String name) {
    try {
      AccountEntity? account = repository.firstWhere((element) => element.name == name);
      return Future.value(account);
    } catch (e) {
      return Future.value(null);
    }
  }

  @override
  Future<void> saveLoginAccount(AccountEntity accountEntity) {
    loginAccount = accountEntity;
    return Future.value();
  }
}
